package com.bdqn;

import com.bdqn.dao.SysUser;
import com.bdqn.service.SysUserService;
import org.apache.log4j.Logger;
import org.aspectj.bridge.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    private ArrayList<SysUser> sysUserslist = new ArrayList<SysUser>();

    private ArrayList<SysUser> userList = new ArrayList<SysUser>();

    public SysUserController(){
        try {
            sysUserslist.add(new SysUser(5,"zhaojiang","赵静","5555555",1,"13054784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserslist.add(new SysUser(4,"wanglin","王林","4444444",1,"13054784444","北京市学院路",1,1,new Date(),1,new Date()));
            sysUserslist.add(new SysUser(1,"test001","测试用户001","1111111",1,"13054784441","北京市朝阳区",1,1,new Date(),1,new Date()));
            sysUserslist.add(new SysUser(2,"zhaoyan","赵燕","2222222",1,"13054784442","北京市海定淀区",1,1,new Date(),1,new Date()));
            sysUserslist.add(new SysUser(3,"test003","测试用户003","1111111",1,"13054784443","北京市海定淀区",1,1,new Date(),1,new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //用于返回查询到的用户数据
    private ArrayList<SysUser> queryUserList = new ArrayList<SysUser>();
    //查询所有用户
    @GetMapping("/list")
    public String list(Model model){
        logger.info("当查询条件为空时，查询用户信息");
        queryUserList.clear();
        queryUserList.addAll(userList);
        model.addAttribute("queryUserList",queryUserList);
        return "sysUserList";
    }

    //根据条件查询部分用户
    @PostMapping("/list")
    public String list(@RequestParam(value = "realName",required = false) String realName, Model model){
        System.out.println("11");
        logger.info("查询条件：【realName】 = " + realName + ", 查询用户信息");
        queryUserList.clear();
        if (realName != null && !realName.equals("")){
            for (SysUser user:userList){
                if (user.getRealName().indexOf(realName) != -1){
                    queryUserList.add(user);
                }
            }
        }else {
            queryUserList.addAll(userList);
        }
        model.addAttribute("queryUserList",queryUserList);
        return "sysUserList";
    }

    //跳转到登录页面
    @RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("登录方法");
        //调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account,password);
        if (null != sysUser){ //登录成功
            //将登录成功的用户放入session
            session.setAttribute(Controller.UsER_SESSION,sysUser);
            return "redirect:/user/toMain";
        }else {
            //用户不存在，登录失败，跳转到登录页面
            request.setAttribute("error","用户名或密码不正确");
            return "login";
        }
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    /*//一个报出异常的接口
    @RequestMapping("/exLogin")
    private String exLogin(@RequestParam String account,@RequestParam String password){
        SysUser user = sysUserService.login(account,password);
        if (null==user){
            throw new RuntimeException("用户名或密码不正确");
        }
        return "redirect:/user/toMain";
    }*/

    @GetMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,@RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList = null;
        try{
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int TotalCount = sysUserService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList = null;
            roleList = sysRoleService.getRoleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("correntPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

}
